<template>
  <div class="warpper-box">
    <div class="inner_box">
      <el-form :inline="true" size="small" :model="formInline" ref="formInline">
        <el-form-item label="入库时间" prop="time">
           <el-date-picker
            v-model="formInline.time"
            type="daterange"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item
        label="入库类型"
        prop="applyCategoryId"
      >
        <el-cascader
          placeholder="支持搜索，多选"
          filterable
          v-model="formInline.applyCategoryId"
          collapse-tags
          :options="treeData"
          :props="{multiple: true,emitPath: false}"
          clearable
        ></el-cascader>
      </el-form-item>
         <el-form-item label="公司名称" prop="name">
          <el-input v-model="formInline.name" placeholder="公司名称"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="contactPerson">
          <el-input
            v-model="formInline.contactPerson"
            placeholder="姓名"
          ></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="contactPhone">
          <el-input
            v-model="formInline.contactPhone"
            placeholder="电话"
          ></el-input>
        </el-form-item>
        <el-form-item label="审核状态" prop="storeStatus">
          <el-select v-model="formInline.storeStatus" placeholder="审核状态">
            <el-option label="全部" value=""></el-option>
            <el-option label="待审核" value="0"></el-option>
            <el-option label="已通过" value="1"></el-option>
            <el-option label="已驳回" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="formInline.email" placeholder="邮箱"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="loadList(true)">搜索</el-button>
           <el-button type="primary" icon="el-icon-setting" @click="reset('formInline')">重置</el-button>
          <el-button type="danger" icon="el-icon-delete" :disabled="selectItem.length == 0" @click="delBatch()">批量删除</el-button>
          <el-button type="primary" icon="el-icon-upload" :disabled="tables.tableData.length == 0" @click="xlsxExport()">导出Excel</el-button>
        </el-form-item>
      </el-form>
      <supplier-common-list
       ref="createSupplier"
       :tableData="tables.tableData" 
       :tableLabel="tables.tableLabel"
       :models="tables" 
       :key="tableKey"
       @on-search-click="loadList"
       @on-selection-click="selectionChange"
       @on-detail-click="supplierDetailClick"
       @on-store-detail-click="onStoreDetailClick"
       @on-apply-click="apply"
       @on-del-click="del"
       />
    </div>

      <supplierDetail ref="createSupplierDetail" />
      <infoStore ref="createInfoStore" />
     <approveStore ref="createApproveStore" title="入库审核" storeTitle="入库资料" @onOk="loadList" :isStoreInfo="true"/>

  </div>
</template>

<script>
import moment from "moment";
import { mapGetters, mapActions } from "vuex";
import { getSupplierStorePage, supplierSignDel, delStoreApplyBatch, getSupplierCategoryTree } from "@/api/supplier_api";
import { checkEmail, checkPhone, TreeArrar } from "@/utils/index";
import { SUPPLIER_STORE_LABEL } from "@/views/supplier/supplierModel/config";
import supplierDetail from '@/views/supplier/supplierModel/supplier_detail.vue'
import supplierCommonList from "@/views/supplier/supplierModel/supplier_common_list.vue"
import approveStore from "@/views/supplier/supplierModel/approve_store.vue"
  import infoStore from '@/views/supplier/supplierModel/info_store.vue'
export default {
  components: {
    supplierDetail,
    supplierCommonList,
    approveStore,
    infoStore
  },
  data() {
    return {
      formInline: {
        name: "",
        applyCategoryId:[],
        contactPerson: "",
        contactPhone: "",
        storeStatus: "0",
        email: "",
        time:[]
      },
      treeData:[],
      tableKey: 0,
      tables:{
        total: 0,
        isStore:true,
        tableData: [],
        tableLabel:SUPPLIER_STORE_LABEL
      },
      models: {
        pageNum: 1,
        pageSize: 10
      },
      selectItem:[]
    };
  },
  computed: {
    ...mapGetters(["findType"])
  },
  mounted() {
    this.loadList(true);
    this.categoryList()
  },
  methods: {
    async categoryList() {
        const { code, data } = await getSupplierCategoryTree();
      if (code == 200) {
       if (data && data.length) {
          let NewData = data.map((ele) => TreeArrar(ele))
         this.treeData = NewData
       } 
     }
    },
    async loadList(formData) {
      let param = {};
      if (typeof formData === 'boolean') {
        this.models.pageNum = 1;
        this.models.pageSize = 10;
        if (this.$refs.createSupplier) {
          this.$refs.createSupplier.clearSelected()
        }
      }
      if (typeof formData === 'object') {
         this.models.pageNum = formData.pageNum;
        this.models.pageSize = formData.pageSize;
        if (this.$refs.createSupplier) {
          this.$refs.createSupplier.clearSelected()
        }
      }
      if (
        this.formInline.contactPhone &&
        !checkPhone(this.formInline.contactPhone)
      ) {
        this.$message.error("联系电话输入格式有误");
        return;
      }
      if (this.formInline.email && !checkEmail(this.formInline.email)) {
        this.$message.error("邮箱输入格式有误");
        return;
      }
      if (this.formInline.applyCategoryId&&this.formInline.applyCategoryId.length) {
        param.applyCategoryIds = this.formInline.applyCategoryId
      }

      if (this.formInline.time && this.formInline.time.length) {
        param.storeStartTime = this.formInline.time[0]
        param.storeEndTime = this.formInline.time[1]
      }

      param.contactPhone = this.formInline.contactPhone;
      param.email = this.formInline.email;
      param.contactPerson = this.formInline.contactPerson;
      param.name = this.formInline.name;
      param.storeStatus = this.formInline.storeStatus;
      param.pageNum = this.models.pageNum
      param.pageSize = this.models.pageSize;
      param.storeType = '1';
    //  param.queryType = '2'
      const { code, data } = await getSupplierStorePage(param);
      if (code == 200) {
        data.list.forEach(v => {
          v.storeApply = true
          v.storeSupplierId = v.id
          v.id = v.applyId
        })
        this.tables.tableData = data.list
        this.tables.total = data.total
      }
    },
    onOk(result) {
      this.tableKey++
      this.loadList(result);
    },
    reset(formName){
      this.$refs[formName].resetFields();
      this.loadList(true);
    },
    del(row) {
      let name = `确认删除公司名称为【${row.name}】？`;
      let param = {};
      param.id = row.id;
      this.$confirm(name, "温馨提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          const { code, msg } = await supplierSignDel(param);
          if (code === 200) {
            this.loadList(true);
          }
        })
        .catch(() => {});
    },
    selectionChange(arr){
        this.selectItem = arr;
      },
    delBatch() {
      if(this.selectItem.length === 0){
            return this.$message.error("请勾选要删除的数据！");
        }
        this.$confirm("确认删除", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(async () => {
          const ids = this.selectItem.map(v => v.id)
          const {code} = await delStoreApplyBatch(ids);
          if(code === 200){
            this.$message.success("操作成功");
            this.loadList(true);
          }
        }).catch(() => {});
    },
    supplierDetailClick(row) {
      this.$refs.createSupplierDetail.openDetail(row,1)
    },
    onStoreDetailClick(row) {
      this.$refs.createInfoStore.openDetail(row)
    },
    apply(row) {
      this.$refs.createApproveStore.openStoreForm(row)
    },
    async xlsxExport() {
       let param = {};
       if (
        this.formInline.contactPhone &&
        !checkPhone(this.formInline.contactPhone)
      ) {
        this.$message.error("联系电话输入格式有误");
        return;
      }
      if (this.formInline.email && !checkEmail(this.formInline.email)) {
        this.$message.error("邮箱输入格式有误");
        return;
      }
      if (this.formInline.applyCategoryId&&this.formInline.applyCategoryId.length) {
        param.applyCategoryIds = this.formInline.applyCategoryId
      }

      if (this.formInline.time && this.formInline.time.length) {
        param.storeStartTime = this.formInline.time[0]
        param.storeEndTime = this.formInline.time[1]
      }

      param.contactPhone = this.formInline.contactPhone;
      param.email = this.formInline.email;
      param.contactPerson = this.formInline.contactPerson;
      param.name = this.formInline.name;
      param.storeStatus = this.formInline.storeStatus;
      param.pageNum = 1
      param.pageSize = this.tables.total;
      param.storeType = '1';
     const { code, data } = await getSupplierStorePage(param);
      let fields = {}
      SUPPLIER_STORE_LABEL.forEach(v => {
       if (v.type == 'on') {
        fields['index'] = v.label
       } else {
         if (v.prop) {
          fields[v.prop] = v.label
        }
       }
      })
      const entries = Object.entries(fields);
      if (entries.length > 0) {
        const firstEntry = entries.shift();
        entries.push(firstEntry);
      }
     const header = Object.fromEntries(entries);
       const manualWidthColumns = [
        { width: 10 },
        { width: 35 },
        { width: 40 },
        { width: 15 },
        { width: 15 },
        { width: 25 },
        { width: 15 },
        { width: 15 },
        { width: 30 },
        { width: 50 },
        { width: 30 }
       ];

       data.list.forEach((v, i) => {
          v.index = (i + 1)
          if (v.storeApplyTime) {
            let time = moment(v.storeApplyTime).format("YYYY-MM-DD");
            v.storeApplyTime = time
          }
          if (v.storeCheckTime) {
            let time = moment(v.storeCheckTime).format("YYYY-MM-DD");
            v.storeCheckTime = time
          }

          if (v.storeStatus) {
            if (v.storeStatus === '1') {
              v.storeStatus = '已通过'
            } else if (v.storeStatus === '0') {
              v.storeStatus = '待审核'
            } else if (v.storeStatus === '2') {
              v.storeStatus = '已驳回'
            }
          }
        })
       
      if (this.$refs.createSupplier) {
        this.$refs.createSupplier.clearSelected()
        this.$refs.createSupplier.exportXlsx(header,data.list,manualWidthColumns,'入库申请列表')
      }

    }
  }
};
</script>
<style scoped>
.duo-file{
  display: flex;
  flex-wrap: wrap;
}
</style>